package com.lvsc.sdaplacefinder.service;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.AsyncTask;
import android.util.Log;

import com.lvsc.sdaplacefinder.models.ImageToUpload;
import com.lvsc.sdaplacefinder.util.WebServiceUtil;

public class ImageUploaderTask extends AsyncTask<String, Void, Void> {
	List<ImageToUpload> list;
	private Long id;

	public ImageUploaderTask(List<ImageToUpload> list, Long id) {
		this.list = list;
		this.id = id;
	}

	@Override
	protected Void doInBackground(String... arg0) {
		for (ImageToUpload imageToUpload : list) {

			String path = imageToUpload.getPath();
			Bitmap mImageBitmap = imageToUpload.getImage();

			HttpURLConnection connection = null;
			DataOutputStream outputStream = null;

			String urlServer = WebServiceUtil.SDA_REST_HOST + "upload/" + id;

			String lineEnd = "\r\n";
			String twoHyphens = "--";
			String boundary = "*****";

			int bytesRead, bytesAvailable, bufferSize;
			byte[] buffer;
			int maxBufferSize = 1 * 1024 * 1024;

			try {

				File file = new File(path);

				if (!file.exists()) {
					file.createNewFile();
				}

				FileOutputStream stream = new FileOutputStream(file);
				mImageBitmap.compress(CompressFormat.PNG, 0, stream);
				stream.flush();
				stream.close();

				FileInputStream fileInputStream = new FileInputStream(file);

				URL url = new URL(urlServer);
				connection = (HttpURLConnection) url.openConnection();

				// Allow Inputs & Outputs
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setUseCaches(false);

				// Enable POST method
				connection.setRequestMethod("POST");

				connection.setRequestProperty("Connection", "Keep-Alive");
				connection.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);

				outputStream = new DataOutputStream(
						connection.getOutputStream());
				outputStream.writeBytes(twoHyphens + boundary + lineEnd);
				String fileName = "upload";
				outputStream
						.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
								+ fileName + "\"" + lineEnd);
				outputStream.writeBytes(lineEnd);

				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];

				// Read file
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				while (bytesRead > 0) {
					outputStream.write(buffer, 0, bufferSize);
					bytesAvailable = fileInputStream.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fileInputStream.read(buffer, 0, bufferSize);
				}

				outputStream.writeBytes(lineEnd);
				outputStream.writeBytes(twoHyphens + boundary + twoHyphens
						+ lineEnd);

				// Responses from the server (code and message)
				int serverResponseCode = connection.getResponseCode();
				String serverResponseMessage = connection.getResponseMessage();

				fileInputStream.close();
				outputStream.flush();
				outputStream.close();
			} catch (Exception ex) {
				// Exception handling
				Log.e("register", "Exception", ex);
			}
		}
		return null;
	}

}